package com.pancm.test.ffmpeg;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;

public class AudioFormatDetector {

    public static String getAudioFormat(String filePath) {
        try (FileInputStream fis = new FileInputStream(filePath)) {
            byte[] headerBytes = new byte[12]; // 读取头部12个字节
            int bytesRead = fis.read(headerBytes);
            if (bytesRead < 12) {
                return "Unknown";
            }

            String headerString = new String(headerBytes, StandardCharsets.ISO_8859_1);

            // 判断是否为M4A (AAC-ISO Base Media File)
            if (headerString.contains("ftyp") && (headerString.contains("mp42") || headerString.contains("isom"))) {
                return "M4A";
            }

            // 判断是否为MP3（带ID3标签）
            if (headerString.startsWith("ID3")) {
                return "MP3";
            }

            // 判断是否为MP3（帧头以0xFF 0xFB开始）
            if ((headerBytes[0] & 0xFF) == 0xFF && (headerBytes[1] & 0xE0) == 0xE0) {
                return "MP3";
            }

            return "Unknown";

        } catch (IOException e) {
            e.printStackTrace();
            return "Error";
        }
    }

    private static boolean isM4AFile(File file) throws IOException {
        try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
            if (raf.length() < 12) return false;

            raf.seek(4);
            byte[] ftyp = new byte[4];
            raf.read(ftyp);
            if (!"ftyp".equals(new String(ftyp, StandardCharsets.US_ASCII))) {
                return false;
            }

            raf.seek(8);
            byte[] brand = new byte[4];
            raf.read(brand);
            String brandStr = new String(brand, StandardCharsets.US_ASCII);
            return brandStr.equals("M4A ") || brandStr.equals("mp42")
                    || brandStr.equals("isom") || brandStr.equals("M4B ");
        }
    }

    public static void main(String[] args) throws IOException {
        String filePath = "1 (2).mp3"; // 替换为你的文件路径
        String format = getAudioFormat(filePath);
        System.out.println("Detected format: " + format);
        String filePath2 = "1 (2) - 副本.m4a"; // 替换为你的文件路径
        String format2 = getAudioFormat(filePath2);
        System.out.println("Detected format: " + format2);
        System.out.println(isM4AFile(new File(filePath)));
        System.out.println(isM4AFile(new File(filePath2)));
    }
}